﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace FaWorks.WebSite.Controllers
{
    public class ScriptController : Controller
    {
        public ActionResult RenderModel(string type)
        {
            Assembly assembly = Assembly.Load("FaWorks.WebSite");
            Type t = assembly.GetType("FaWorks.WebSite.Models." + type);

            StringBuilder sb = new StringBuilder();
            foreach (PropertyInfo pi in t.GetProperties()) {
                sb.AppendFormat(",\"{0}\": {{ \"type\": \"{1}\", \"displayType\": \"{2}\" }}", ToCamelCase(pi.Name), GetJsTypeName(pi.PropertyType.Name), "");
            }


            string template;
            using (TextReader tr = new StreamReader(Server.MapPath("~/Javascript/lib/template/Model.js")))
            {
                template = tr.ReadToEnd();
            }
            template = template.Replace("[Name]", t.Name);
            template = template.Replace("[Properties]", sb.ToString().Substring(1));

            return JavaScript(template);
        }

        public static string ToCamelCase(string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return s;
            }
            if (s == s.ToUpper()) {
                return s.ToLower();
            }
            if (!char.IsUpper(s[0]))
            {
                return s;
            }
            string str = null;
            str = char.ToLower(s[0], CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture);
            if (s.Length > 1)
            {
                str = str + s.Substring(1);
            }
            return str;
        }



        private string GetJsTypeName(string typeName){
            switch (typeName) { 
                case "Int32":
                    return "string";
                default:
                    return typeName.ToLower();
            }
        }
    }
}
